﻿using AutoMapper;
using MediatR;
using SY.BasicData.Api.Write.Basic.Applications.Cultivation.Command;
using SY.BasicData.Domain.Cultivation;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.Cultivation.CommandHandler
{
    public class UpdateImmunityCommandHandler : IRequestHandler<UpdateImmunityCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ImmunityModel> baseRepository;
        private readonly IMapper mapper;

        public UpdateImmunityCommandHandler(IBaseRepository<ImmunityModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        public  Task<ApiResult<int>> Handle(UpdateImmunityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var imm = baseRepository.GetAll().Where(x => !x.IsDeleted && x.Id == request.Id).FirstOrDefault();
            if (imm == null)
            {
                res.Message = "找不到编号";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);
            }

            imm = mapper.Map(request, imm);

            int a = baseRepository.Update(imm).Result;
            if (a > 0)
            {
                res.Message = "修改免疫信息成功";
                res.Code = ApiEnum.Success;
                res.Data = a;

            }
            else
            {
                res.Message = "修改免疫信息失败";
                res.Code = ApiEnum.Fail;
                res.Data = a;
            }
            return Task.FromResult(res);
        }
    }
}
